package com.ruoyi.web.utils;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.web.domain.WxVo.WxCode;
import com.ruoyi.web.domain.WxVo.WxGetPhoneVo;
import com.ruoyi.web.domain.WxVo.WxInfo;
import com.ruoyi.web.wxConfig.WxConstant;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
* @Project: serve
* @Package com.ruoyi.web.utils
* @Description: TODO(这里用一句话描述这个类的作用)
* @author : GuitarXiaohe
* @date Date : 2023年10月27日 09:49
* @version V1.0
*/

 @Component
public class WxUtils {
    @Resource
    RedisCache redisCache;
    /**
     * 获取微信token
     *
     * @return appid=wx48db18326b277d33
     * 小程序秘钥=0f5a570391583a10f2d7344b727be896
     */
    public String getWxaccess_token(String openId) {
        String url = WxConstant.WX_TOKEN_URL;
        url += "/token?grant_type=client_credential";
        url += "&appid=" + WxConstant.APP_ID;
        url += "&secret=" + WxConstant.SECRET;
        String result = HttpUtil.doGet(url);
        String token = JSON.parseObject(result, WxInfo.class).getAccessToken();
        redisCache.setCacheObject("access_token", token, 1, TimeUnit.HOURS);
        return token;
    }


    /**
     * 解密手机号
     * POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
     */
    public String getWxPhone(String code) throws Exception {
        String accessoToken = getWxaccess_token("access_token");
        String url = WxConstant.WX_PHONE_URL;
        url += "?access_token=" + accessoToken;


        WxCode wxCode = new WxCode();
        wxCode.setCode(code);
        String jsonString = JSON.toJSONString(wxCode);

        String result = HttpUtil.doPost(url, jsonString);


        WxGetPhoneVo wxGetPhoneVo = JSON.parseObject(result, WxGetPhoneVo.class);

        if (wxGetPhoneVo.getErrcode() != 0) {
            throw new Exception("发送消息错误=>" + wxGetPhoneVo.getErrmsg());
        }
        System.out.println(result);
        return wxGetPhoneVo.getPhone_info().getPhoneNumber();
    }


    /**
     * 获取openid
     * @param code
     * @return
     */

    public String getOpenId(String code) {
        String url = WxConstant.WX_OPENIF_URL;
        url += "?appid=" + WxConstant.APP_ID;
        url += "&secret=" + WxConstant.SECRET;
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        String s = HttpUtil.doGet(url);
        return JSON.parseObject(s, WxInfo.class).getOpenId();
    }
}